package com.a.module_storage

import androidx.lifecycle.viewModelScope
import com.alibaba.fastjson.JSONObject
import com.example.myframe.base.repo.EasyHttpRepoKt
import com.example.myframe.base.viewmodel.EasyHttpViewModelKt
import com.google.gson.reflect.TypeToken
import com.a.lib_network.bean.HttpData
import kotlinx.coroutines.launch

/**
 * CREATE BY 黄炜强
 * 2022/7/21 15:09
 * Desc:
 * */
class StorageRequester : EasyHttpViewModelKt<StorageEvent>() {
    private val repo = EasyHttpRepoKt()
    override suspend fun onHandle(event: StorageEvent) {
        val eventId = event.eventId
        val result = event.result
        if (eventId == StorageEvent.EVENT_GET_LIST) {
            repo.get<List<ProductItem>>(event.api, result) {
                if (isSuccess(result, it)) {
                    result.data.productItemList = it
                }
                viewModelScope.launch {
                    sendResult(event)
                }
            }
        } else if (eventId == StorageEvent.GET_TYPE_LIST) {
            repo.get<HttpData<JSONObject>>(event.api, result) {
                if (isSuccess(result, it)) {
                    result.data.productTypeList =
                        it.data.getObject<MutableList<ProductType>>(
                            "productTypeList",
                            object : TypeToken<MutableList<ProductType>>() {}.type
                        )
                    result.data.productTypeList.add(
                        0,
                        ProductType("", "全部分类")
                    )
                }
                viewModelScope.launch {
                    sendResult(event)
                }
            }
        }
    }
}